<template>
  <div>
    <div id="carShop" style="height: 100%;padding-top: 50px;box-sizing: border-box;
        display: flex;flex-direction: column;">
        <div style="width: 100%;display: flex;justify-content: space-between;box-sizing: border-box;padding: 10px 30px 10px 10px;align-items: center;">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-button type="info" size="mini" icon="el-icon-delete" circle @click="delAllForCart"></el-button>
        </div>
        <div class="cartList" v-for="cartItem in cartList.cartItem" :key="cartItem.goodsId">
          <div style="display: flex;align-items: center;width: 10%;justify-content: center;">
            <el-checkbox v-model="cartItem.isCheck" @change="checkedChange(cartItem.goodsId,cartItem.isCheck)"/>
          </div>
          <div><img :src="cartItem.goodsImg" style="width: 100%;height: 100%;"></div>
          <div style="box-sizing: border-box;padding: 5px 10px;display: flex;justify-content: space-between;flex-direction: column;flex: 1;">
            <div style="text-align: left;">
              <h2 style="font-size: 18px;">{{cartItem.goodsName}}</h2>
              <p>￥{{cartItem.totalPrice}}.00</p>
            </div>
            <div style="display: flex;justify-content: space-between;">
              <el-input-number v-model="cartItem.count" size="mini" :min="1" :max="(cartItem.count>10)?cartItem.count:10" label="商品数量" @change="itemCheck(cartItem.goodsId,null,cartItem.count)"></el-input-number>
              <el-button type="info" size="mini" icon="el-icon-delete" circle @click="delForCart(cartItem.goodsId)"></el-button>
            </div>
          </div>
        </div>
    </div>
    <div class="settleAccount">
      <div style="flex: 1;align-items: center;display: flex;flex-direction: row-reverse;padding: 0 20px;">
          <span>合计:<span style="font-size: 20px;color: #8d5546;">￥{{cartList.totalAmount!=null?cartList.totalAmount+'.00':0}}</span></span>
      </div>
      <el-button
          plain
          @click="toPay" style="border-radius: 0;display: block;width: 20%;background-color: #732707;color: #fff;">
          结算
        </el-button>
    </div>
    <el-empty id="empty" description="无数据" style="width: 100%; height:80vh;"></el-empty>
    <el-empty id="emptyCar" description="还没有商品,去看看商品吧" style="width: 100%; height:80vh;"></el-empty>
    <el-dialog
      title="提示"
      :visible.sync="loginDialogVisible"
      :before-close="closeDialog" style="width: 100%;">
      <span>请先登录</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loginDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click.native="goLoginPage">登 录</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import qs from 'qs'
  export default{
    name: "ShopCarList",
    data() {
      return{
        isIndeterminate:true,
        checkAll:false,
        cartList:{},
        totalPrice:0,
        checkedCount:0,

        loginDialogVisible:false,
      }
    },
    mounted() {
      this.queryMyCart()
    },

    methods:{
      //判断是否登录方法
      isLogin(){
        this.user = JSON.parse(sessionStorage.getItem("visitor"));
        if(this.user == null || this.user == {}){
          return false
        }
        return true;
      },
      closeDialog(){
        this.loginDialogVisible = false;
      },
      //跳转登录页面
      goLoginPage(){
          sessionStorage.setItem("lastPage","/home/shopCar")
          this.$router.push({
            path: "/userLogin"
          });
      },

      //是否全选
      handleCheckAllChange(val){
        this.isIndeterminate = false
        var ids = [];
        for(let i in this.cartList.cartItem){
            this.cartList.cartItem[i].isCheck = val
            ids.push(this.cartList.cartItem[i].goodsId)
        }
        this.allItemCheck(ids,val)
      },

      //子框显示状态
      checkedChange(goodsId,isChecked){
        //如果全选保证子框显示模式对应
        this.checkAll = this.cartList.cartItem.every((obj) => {
          return obj.checked == true
        })
        //判断是否是渲染方法进入此方法
        if(isChecked!= null){
          //不是渲染方法就是子元素单机事件进入
          if(isChecked){
            this.checkedCount += 1;
          }else{
            this.checkedCount -= 1;
          }
          this.itemCheck(goodsId,isChecked,null)
        }
        this.checkAll = this.checkedCount === this.cartList.cartItem.length;
        this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.cartList.cartItem.length;
      },

      //修改状态数量方法
      itemCheck(goodsId,isChecked,goodsNum){
        // console.log(val)
        var cartList = []
        cartList.push({goodsId,isCheck:isChecked,goodsNum})
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        if(user != null){
          //设置访问后台cookie数据
          this.$cookies.set("userCode",user.userCode);
          this.$cookies.set("token",user.token);
          this.$http.post('/api/CakeShop/cart/itemCheck',cartList).then((res)=>{
            if(res.data.code == 200){
              console.log(res)
              this.queryMyCart()
            }
          })
          //清除相关cookie
          this.$cookies.remove("userCode");
          this.$cookies.remove("token");
        }
      },

      //修改状态数量方法
      allItemCheck(ids,isChecked){
        var cartList = [];
        var empty = null;
        for(var id of ids){
          cartList.push({goodsId:id,isCheck:isChecked,goodsNum:empty})
        }
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        if(user != null){
          //设置访问后台cookie数据
          this.$cookies.set("userCode",user.userCode);
          this.$cookies.set("token",user.token);
          this.$http.post('/api/CakeShop/cart/itemCheck',cartList).then((res)=>{
            if(res.data.code == 200){
              console.log(res)
              this.queryMyCart()
            }
          })
          //清除相关cookie
          this.$cookies.remove("userCode");
          this.$cookies.remove("token");
        }
      },

      delForCart(goodsId){
        var goodsIds = [];
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        goodsIds.push(goodsId);
        console.log(goodsIds)
        if(user != null){
          //设置访问后台cookie数据
          this.$cookies.set("userCode",user.userCode);
          this.$cookies.set("token",user.token);
          this.$http.post('/api/CakeShop/cart/delForCart',goodsIds).then((res)=>{
            if(res.data.code == 200){
              console.log(res)
              this.queryMyCart()
            }
          })
          //清除相关cookie
          this.$cookies.remove("userCode");
          this.$cookies.remove("token");
        }
      },

      delAllForCart(){
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        if(user != null){

          var goodsIds = [];
          for(let i in this.cartList.cartItem){
              goodsIds.push(this.cartList.cartItem[i].goodsId)
          }

          //设置访问后台cookie数据
          this.$cookies.set("userCode",user.userCode);
          this.$cookies.set("token",user.token);
          this.$http.post('/api/CakeShop/cart/delForCart',goodsIds).then((res)=>{
            if(res.data.code == 200){
              console.log(res)
              this.queryMyCart()
            }
          })
          //清除相关cookie
          this.$cookies.remove("userCode");
          this.$cookies.remove("token");
        }
      },

      //查询购物车商品
      queryMyCart(){
        document.getElementById("empty").style.display = 'none'
        document.getElementById("emptyCar").style.display = 'none'
        var self = this
        let num = 0;
        //查询当前用户
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        if(user != null){
          document.getElementById("carShop").style.display = 'flex'
          //设置访问后台cookie数据
          this.$cookies.set("userCode",user.userCode);
          this.$cookies.set("token",user.token);
          if(user!=null){
            this.$http.get("/api/CakeShop/cart/cartList",{
                withCredentials: true,
                Headers:{
                  'Cookie': 'userCode=' + user.userCode
                }
            }).then((res)=>{
              self.cartList = res.data.cartList
              // if(res.data.cartList.cartItem.length>0){
                for(var item of res.data.cartList.cartItem){
                  if(item.isCheck){
                    num += 1;
                  }
                }
              // }
              if(res.data.cartList.cartItem.length == 0){
                document.getElementById("emptyCar").style.display = 'flex';
              }
              self.checkedCount = num
              self.checkedChange()
            })
          }
          //清除相关cookie
          this.$cookies.remove("userCode");
          this.$cookies.remove("token");
        }else{
          document.getElementById("carShop").style.display = 'none'
          document.getElementById("empty").style.display = 'flex'
        }
      },
      //跳转结算页方式
      toPay(){
        var user = JSON.parse(sessionStorage.getItem("visitor"));
        if(this.isLogin()){
          sessionStorage.setItem("lastPage",'/home/shopCar')
          this.$router.push("/settlePage")
        }else{
          this.loginDialogVisible = true
        }
      }
    },
  }
</script>

<style scoped>
  .cartList{
    display: flex;
    width: 100%;
    height: 120px;
    box-sizing: border-box;
    padding: 10px;
    border-top: 1px solid black;
  }
  .settleAccount{
    width: 100%;
    height: 50px;
    display: flex;
    position: fixed;
    bottom: 60px;
    border-top: 1px solid black;
  }
</style>
